<template>
    <div>
        <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="二维码图片解析" name="1">
                <img-upload @getImage="getImage"></img-upload>
            </el-collapse-item>
            <el-collapse-item title="摄像头扫描解析" name="2" :disabled="!isSupportMediaDevices">
                <camera-explain
                  v-if="isSupportMediaDevices"
                  @decodeSuccess="decodeSuccess"
                ></camera-explain>
            </el-collapse-item>
        </el-collapse>
        <el-dialog
            title="二维码解析结果"
            width="700px"
            v-model="showResult"
            :before-close="handleClose"
        >
            <div class="qrcode-context">
                {{ qrcodeData }}
            </div>
            <template #footer>
               <span>
                  <el-button type="primary" @click="copyQRcodeData">复 制</el-button>
               </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { Options, Vue } from 'vue-property-decorator';
import {
  ElButton, ElCollapse, ElCollapseItem, ElDialog, ElMessage,
} from 'element-plus';
import { copyText } from '@/common/utils';
import QrcodeDecoder from '@/common/qrcode-decoder';
import ImgUpload from './img-upload.vue';
import CameraExplain from './camera-explain/index.vue';

@Options({
  components: {
    ElButton,
    ElCollapse,
    ElCollapseItem,
    ElDialog,
    ImgUpload,
    CameraExplain,
  },
})
export default class QRcodeExplain extends Vue {
    qrcodeData = '';

    activeName = '1';

    imageBase = '';

    get isSupportMediaDevices() {
      return !!navigator?.mediaDevices?.getUserMedia;
    }

    get showResult() {
      return !!this.qrcodeData;
    }

    async getImage(imgBase64: string) {
      if (imgBase64) {
        const decoder = new QrcodeDecoder();
        const qrcode = await decoder.decodeByImage(imgBase64);
        if (qrcode) {
          this.decodeSuccess(qrcode.data);
        } else {
          this.decodeError();
        }
      }
    }

    decodeSuccess(data: string) {
      this.qrcodeData = data;
    }

    decodeError() {
      ElMessage.error('图片解析失败');
    }

    copyQRcodeData() {
      if (this.qrcodeData) {
        this.copyText(this.qrcodeData);
      }
      this.handleClose();
    }

    handleClose() {
      this.qrcodeData = '';
    }

    // 文本复制工具函数
    copyText(text: string) {
      const result = copyText(text);
      if (result) {
        ElMessage.success('已复制到剪贴板!');
      } else {
        ElMessage.error('复制遇到了点问题，请重试!');
      }
    }
}
</script>

<style lang='less' scoped>
    .qrcode-context{
        margin: 15px 0;
        font-size: 12px;
        font-weight: 500;
    }
</style>
